package javase.jmx.security.simple.client;

import java.util.HashMap;

import javase.jmx.security.simple.utils.ResourceHelper;

import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class Client {

    @SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
        try {
            System.out.println("\nInitialize the environment map");
            HashMap env = new HashMap();
            String[] credentials = new String[] { "username" , "password" };
            env.put("jmx.remote.credentials", credentials);
            env.put("javax.net.ssl.trustStore", getPathToTruststore());
            env.put("javax.net.ssl.trustStorePassword", "trustword");
            
            System.out.println("\nCreate an RMI connector client and connect it to the RMI connector server");
            JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://localhost:9999/server");
            JMXConnector jmxConnection = JMXConnectorFactory.connect(url, env);

            System.out.println("\nGet an MBeanServerConnection");
            MBeanServerConnection mbeanServerConnection = jmxConnection.getMBeanServerConnection();

            // Get domains from MBeanServer
            System.out.println("\nDomains:");
            String domains[] = mbeanServerConnection.getDomains();
            for (int i = 0; i < domains.length; i++) {
                System.out.println("\tDomain[" + i + "] = " + domains[i]);
            }

            System.out.println("\nClose the connection to the server");
            jmxConnection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    private static String getPathToTruststore() {
    	return ResourceHelper.getResourceLocation("javase/jmx/security/simple/config/truststore");
    }
}
